package com.beijiteshop.shop.ui.search.fragment

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.beijiteshop.libcommon.base.adapter.showEmpty
import com.beijiteshop.libcommon.base.adapter.showError
import com.beijiteshop.libcommon.base.adapter.showLoading
import com.beijiteshop.libcommon.base.adapter.showNetError
import com.beijiteshop.libcommon.ext.databinding.bindView
import com.beijiteshop.shop.R
import com.beijiteshop.shop.app.PageIndex
import com.beijiteshop.shop.base.BaseContainerFragment
import com.beijiteshop.shop.databinding.FragmentSearchBinding
import com.beijiteshop.shop.model.entity.ProductItemEntity
import com.beijiteshop.shop.ui.detail.ProductDetailFragment
import com.beijiteshop.shop.ui.home.adapter.ProductAdapter
import com.beijiteshop.shop.ui.order.fragment.OrderConfirmFragment
import com.beijiteshop.shop.ui.search.vm.SearchVM
import com.beijiteshop.shop.utils.HomeGridItemDecoration
import org.koin.android.viewmodel.ext.android.viewModel

/**
 * @Author LiaoZhongKai
 * @Date 2021/3/11 9:55
 * @Description 搜索页面
 */
class SearchFragment : BaseContainerFragment(R.layout.fragment_search) {

    companion object{

        const val BUNDLE_KEY = "bundle_key"
        private const val INIT_PAGE = 1

        fun newInstance(key: String): SearchFragment{
            return SearchFragment().apply {
                arguments = Bundle().apply {
                    putString(BUNDLE_KEY,key)
                }
            }
        }
    }

    private val mBinding by bindView<FragmentSearchBinding>()
    private var mAdapter = ProductAdapter(mutableListOf())
    private val mSearchVM: SearchVM by viewModel()

    private var mPage = INIT_PAGE
    private var mKeyword = ""

    override fun onLazyLoad() {
        searchHomeData()
    }

    override fun initView(view: View) {
        mKeyword = arguments?.getString(BUNDLE_KEY)?:""
        initRV()
    }

    override fun initData() {
    }

    override fun initEvent() {
        startObserve()
    }

    private fun searchHomeData(){
        if (mKeyword.isNotEmpty()){
            mAdapter.showLoading()
            mSearchVM.search(mPage,mKeyword)
        }
    }

    private fun requestData(){
        if (mKeyword.isNotEmpty()){
            mSearchVM.search(mPage,mKeyword)
        }
    }

    private fun initRV(){
        mAdapter.apply {

            loadMoreModule.setOnLoadMoreListener {
                mPage++
                requestData()
            }

            setGridSpanSizeLookup { _, _, position ->
                return@setGridSpanSizeLookup mAdapter.data[position].spanSize
            }

            setOnItemClickListener { _, view, position ->
                val bundle = Bundle().apply {
                    putParcelable(ProductDetailFragment.BUNDLE_PRODUCT,data[position].data)
                }
                startActivity(PageIndex.PRODUCT_DETAIL,bundle)
            }
        }

        mBinding.searchRv.apply {
            addItemDecoration(HomeGridItemDecoration(10))
            layoutManager = GridLayoutManager(requireContext(),2)
            adapter = mAdapter
        }
    }

    private fun startObserve(){

        mSearchVM.apply {
            liveProducts.observeKt { data ->
                if (mPage == INIT_PAGE){
                    mAdapter.setNewInstance(data)
                }else{
                    updateRVState(false,data)
                }
            }

            liveEmpty.observeKt {
                if (mPage == INIT_PAGE){
                    mAdapter.showEmpty(it){
                        searchHomeData()
                    }
                }else{
                    updateRVState(false,null)
                }
            }

            liveError.observeKt {
                if (mPage == INIT_PAGE){
                    mAdapter.showError(it){
                        searchHomeData()
                    }
                }else{
                    updateRVState(true,null)
                }
            }

            liveNetError.observeKt {
                if (mPage == INIT_PAGE){
                    mAdapter.showNetError(it){
                        searchHomeData()
                    }
                }else{
                    updateRVState(true,null)
                }
            }
        }
    }

    /**
     * 更新列表加载状态
     */
    private fun updateRVState(error: Boolean,data: MutableList<ProductItemEntity>?){
        if (error){
            if (mAdapter.loadMoreModule.isLoading){
                mAdapter.loadMoreModule.loadMoreFail()
            }
        }else{
            if (mAdapter.loadMoreModule.isLoading){
                if (data.isNullOrEmpty()){
                    mAdapter.loadMoreModule.loadMoreEnd()
                }else{
                    mAdapter.addData(data)
                    mAdapter.loadMoreModule.loadMoreComplete()
                }
            }
        }
    }

}